global restrdir "U:\data"
global public "R:\Public"
global rand "R:\Public\Contributions\Rand\RandHRS2016ER2\stata"
global output "U:\output"


use $restrdir/SSA_mortality_2010, clear

*Compute annuity factors by age and sex

gen annfactor_1 = .
gen annfactor_2 = .

keep if age>=48

forvalues a = 48/80{
qui{
	gen interest_adj = (1.029*1.028)^(`a'-age)
	gen surv_`a'_1 = (1-deathp) if sex==1 & age==`a'
	gen surv_`a'_2 = (1-deathp) if sex==2 & age==`a'
	egen temp = max(surv_`a'_1) 
	replace surv_`a'_1 = temp if surv_`a'_1==.
	drop temp
	egen temp = max(surv_`a'_2) 
	replace surv_`a'_2 = temp if surv_`a'_2==.
	drop temp
	gen surv = 1-deathp
	gen cond_surv_`a'_1 = surv/surv_`a'_1 if sex==1
	gen cond_surv_`a'_2 = surv/surv_`a'_2 if sex==2

	*Sum up
	gen temp = interest_adj*cond_surv_`a'_1
	egen annfactor_`a'_1 = sum(temp) if age>=`a'
	drop temp
	gen temp = interest_adj*cond_surv_`a'_2
	egen annfactor_`a'_2 = sum(temp) if age>=`a'
	drop temp

	replace annfactor_1 = annfactor_`a'_1 if age==`a' & sex==1
	replace annfactor_2 = annfactor_`a'_2 if age==`a' & sex==2
	drop interest_adj surv_`a'* surv cond_surv* annfactor_`a'*
	}
}

keep age sex annfactor*
egen annfactor = rowmin(annfactor_1 annfactor_2)
drop annfactor_1 annfactor_2

save $restrdir/annfactors, replace
